package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.article.IArticleClient;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmDownUpDto;
import com.heima.model.wemedia.dtos.WmNewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.*;
import com.heima.model.wemedia.vos.WmNewsAuthVo;
import com.heima.utils.thread.AdminThreadLocalUtil;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@GlobalTransactional    // 分布式事务
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IArticleClient articleClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 获取当前登录人的信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        // 登录人信息为空
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        page = page(page, Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getUserId, wmUser.getId())
                .eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus())
                .like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword())
                .eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId())
                .between(dto.getBeginPubDate() != null && dto.getEndPubDate() != null,
                        WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate())
                .orderByDesc(WmNews::getPublishTime));
        // 返回结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 发布文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(@RequestBody WmNewsDto dto) {
        // 参数校验
        if (dto == null || dto.getContent() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 创建对象并拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // 获取上传的封面图片
        List<String> dtoImages = dto.getImages();
        // 获取文章内容中的图片地址
        List<String> contentImgPaths = getImagesInContent(wmNews.getContent());
        // 如果当前封面类型为-1，自动时，从文章中截取图片
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            // 多图
            if (contentImgPaths.size() >= 3) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                dtoImages = contentImgPaths.stream().limit(3).collect(Collectors.toList());
            } else if (contentImgPaths.size() >= 1 && contentImgPaths.size() < 3) {
                // 单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                dtoImages = contentImgPaths.stream().limit(1).collect(Collectors.toList());
            } else {
                // 无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
        }
        // 封面图片类型转换，list -> string，以逗号分割
        if (dtoImages != null && dtoImages.size() > 0) {
            String images = StringUtils.join(dtoImages, ",");
            wmNews.setImages(images);
        }
        // 新增或修改文章
        saveOrUpdateNews(wmNews);
        // 判断是否为草稿。是，结束方法
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 不是草稿
        // 关联内容中的图片与素材的关系
        saveWmNewsMaterial(wmNews.getId(), contentImgPaths, WemediaConstants.WM_CONTENT_REFERENCE);
        // 关联封面图片与素材的关系
        if (dtoImages != null && dtoImages.size() > 0) {
            saveWmNewsMaterial(wmNews.getId(), contentImgPaths,
                    WemediaConstants.WM_COVER_REFERENCE);
        }

        // 审核文章
//        wmNewsAutoExamineService.autoExamineWmNews(wmNews.getId());

        // 异步调用，添加任务到延迟队列中
        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult details(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .eq(WmNews::getId, id));
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 返回结果
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNews(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .eq(WmNews::getId, id));
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 当前文章已发布，不能删除
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(501, "文章已发布，不能删除");
        }
        // 删除文章
        removeById(id);
        // 如果不为草稿，删除素材表中的信息
        if (!wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            // 删除文章素材表中的信息
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, id));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmDownUpDto dto) {
        // 参数校验
        if (dto.getId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询
        WmNews wmNews = getOne(Wrappers.<WmNews>lambdaQuery()
                .eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId())
                .eq(WmNews::getId, dto.getId()));
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 当前文章不是已发布状态
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            // 不能上下架
            return ResponseResult.errorResult(501, "当前文章不是发布状态，不能上下架");
        }
        // 修改文章内容
        if (dto.getEnable() != null && (dto.getEnable() == 0 || dto.getEnable() == 1)) {
            wmNews.setEnable(dto.getEnable());  // 更改为已下架或已上架
            updateById(wmNews);
        }
        // 发送消息到kafka
        if (wmNews.getId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", wmNews.getEnable());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                    JSON.toJSONString(map));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 关联图片与素材的关系
     *
     * @param id
     * @param imgPaths
     * @param type
     */
    private void saveWmNewsMaterial(Integer id, List<String> imgPaths, Short type) {
        if (imgPaths != null && imgPaths.size() > 0) {
            // 根据文章图片地址，得到图片信息
            List<WmMaterial> wmMaterialList =
                    wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl,
                            imgPaths));
            // 判断素材是否有效
            if (wmMaterialList == null || wmMaterialList.size() == 0) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            // 素材数量不匹配
            if (imgPaths.size() != wmMaterialList.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
            }
            // 得到图片id集合
            List<Integer> imgIdList =
                    wmMaterialList.stream().map(WmMaterial::getId).collect(Collectors.toList());
            // 保存到数据库中
            wmNewsMaterialMapper.saveRelations(id, imgIdList, type);
        }
    }

    /**
     * 获取文章内容中的图片信息
     *
     * @param content
     * @return
     */
    private List<String> getImagesInContent(String content) {
        List<String> images = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        maps.stream().forEach(map -> {
            if (map.get("type").equals(WemediaConstants.WM_NEWS_TYPE_IMAGE)) {
                String imgPath = (String) map.get("value");
                images.add(imgPath);
            }
        });
        return images;
    }

    /**
     * 新增或修改文章
     *
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        // 补全信息
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);    // 默认为上架 1
        // 判断表中是否存在id
        WmNews dbNews = getById(wmNews.getId());
        if (dbNews == null) {
            // 新增文章
            save(wmNews);
        } else {
            // 存在，删除已关联素材表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            // 修改文章
            updateById(wmNews);
        }
    }

    /**
     * 管理端查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult listAuth(WmNewsAuthDto dto) {
        // 检查参数
        dto.checkParam();
        // 查询是否登录
        AdUser adUser = AdminThreadLocalUtil.getUser();
        if (adUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        page = page(page, Wrappers.<WmNews>lambdaQuery()
                .like(StringUtils.isNotEmpty(dto.getTitle()), WmNews::getTitle, dto.getTitle())
                .eq(dto.getStatus()!=null,WmNews::getStatus,dto.getStatus())
                .orderByDesc(WmNews::getCreatedTime));
        // 封装对象，并赋值
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),
                (int) page.getTotal());
        // 循环创建vo对象并拷贝
        List<WmNews> wmNewsList = page.getRecords();
        List<WmNewsAuthVo> wmNewsAuthVoList = wmNewsList.stream().map(wmNews -> {
            WmNewsAuthVo wmNewsAuthVo = new WmNewsAuthVo();
            BeanUtils.copyProperties(wmNews, wmNewsAuthVo);
            // 查询作者名称
            String authorName = wmUserMapper.selectById(wmNews.getUserId()).getName();
            wmNewsAuthVo.setAuthorName(authorName);
            return wmNewsAuthVo;
        }).collect(Collectors.toList());
        // 赋值
        responseResult.setData(wmNewsAuthVoList);
        // 返回结果
        return responseResult;
    }

    /**
     * 管理端查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult detailsAuth(Integer id) {
        // 检查参数
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询单个文章详细
        WmNews wmNews = getById(id);
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 创建对象并拷贝
        WmNewsAuthVo wmNewsAuthVo = new WmNewsAuthVo();
        BeanUtils.copyProperties(wmNews,wmNewsAuthVo);
        // 查询作者名称
        String authorName = wmUserMapper.selectById(wmNews.getUserId()).getName();
        wmNewsAuthVo.setAuthorName(authorName);
        // 返回结果
        return ResponseResult.okResult(wmNewsAuthVo);
    }

    /**
     * 文章人工审核成功
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsAuthPass(WmNewsAuthDto dto) {
        // 检查参数
        if (dto.getId() == null || dto.getStatus() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询文章
        WmNews wmNews = getById(dto.getId());
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 修改状态和审核失败原因
        wmNews.setStatus(dto.getStatus().shortValue());
        // 修改操作
        updateById(wmNews);
        // 创建APP端的文章信息
        saveAppArticle(wmNews);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存app端的相关文章数据
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        // 属性拷贝
        BeanUtils.copyProperties(wmNews, dto);
        // 文章布局
        dto.setLayout(wmNews.getType());
        // 频道名称
        WmChannel wmChannel = wmChannelMapper.selectById(dto.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }
        // 作者id和作者名称
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId().longValue());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }
        // 文章id，如果审核通过，有文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        // 创建时间
        dto.setCreatedTime(new Date());
        // 执行方法并返回
        articleClient.saveArticle(dto);
    }

    /**
     * 文章人工审核失败
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsAuthFail(WmNewsAuthDto dto) {
        // 检查参数
        if (dto.getId() == null || dto.getStatus() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询文章
        WmNews wmNews = getById(dto.getId());
        // 文章不存在
        if (wmNews == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 修改状态和审核失败原因
        wmNews.setStatus(dto.getStatus().shortValue());
        wmNews.setReason(dto.getMsg());
        // 修改操作
        updateById(wmNews);
        // 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}